﻿using System.Drawing;
using System.Windows.Forms;
using PlusPlusPaint.Layers;
using PlusPlusPaint.Layers.VisualObjects;

namespace PlusPlusPaint.Tools
{
    class TextEditingTool : VisualObjectLayerStoringTool
    {
        #region properties
        public override bool DemandsNewLayer
        {
            get
            {
                return false;
            }
        }

        public override bool AcceptsNewLayer
        {
            get
            {
                return true;
            }
        }
        #endregion

        #region overrides
        public override bool AcceptableLayer(Layers.ILayer l)
        {
            VisualObjectLayer vol = l as VisualObjectLayer;
            if (vol == null)
                return false;
            return vol.AcceptsMostText;
        }

        public override void GiveAccessToLayer(VisualObjectLayer l, Point p)
        {
            base.GiveAccessToLayer(l, p);
            this.Layer.Invoke<TextArea>((area) =>
            {
                if (area.Text == "") // On the first click, let's move it.
                    area.Location = p;
            });
        }

        public override Layers.ILayer SuggestNewLayer()
        {
            return new VisualObjectLayer();
        }

        public override void HandleKeyPressed(KeyPressEventArgs kpea)
        {
            if (this.Layer == null)
                return;
            switch (kpea.KeyChar) // Escape key pressed
            {
                case '\x1B': // escape
                    this.Done = true;
                    break;
                case '\x08': // backspace
                    this.Layer.Invoke<TextArea>((area) =>
                    {
                        if (area.Text != "")
                            area.Text = area.Text.Substring(0, area.Text.Length - 1);
                    });
                    break;
                case '\r':
                    this.Layer.Invoke<TextArea>((area) =>
                        area.Text += "\r\n"
                    );
                    break;
                default:
                    this.Layer.Invoke<TextArea>((area) =>
                        {
                            area.PutChar(kpea.KeyChar);
                            area.Colour = this.Colour;
                        });
                    break;
            }
            this.Layer.Invalidate();
        }
        #endregion
    }
}
